package http

import (
	roleApp "furniture-server-gin/api/pkg/application/role"
	"net/http"

	"github.com/gin-gonic/gin"
)

type roleController struct {
	roleService *roleApp.Service
}

// NewRoleController 创建角色控制器
func NewRoleController(roleService *roleApp.Service) *roleController {
	return &roleController{
		roleService: roleService,
	}
}

// CreateRole 创建角色
func (c *roleController) CreateRole(ctx *gin.Context) {
	var req struct {
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := c.roleService.CreateRole(req.Name, req.Description); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusCreated, gin.H{"message": "Role created successfully"})
}

// GetRoles 获取所有角色
func (c *roleController) GetRoles(ctx *gin.Context) {
	roles, err := c.roleService.GetAllRoles()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"roles": roles})
}

// GetRole 获取单个角色
func (c *roleController) GetRole(ctx *gin.Context) {
	id := ctx.Param("id")

	role, err := c.roleService.GetRoleByID(id)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "Role not found"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"role": role})
}
